package cn.wolfcode.wolf2world.service.impl;

import cn.wolfcode.wolf2world.domain.Spot;
import cn.wolfcode.wolf2world.query.SpotQueryObject;
import cn.wolfcode.wolf2world.repository.SpotRepository;
import cn.wolfcode.wolf2world.service.SpotService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @author 杨兴健
 * @Date 2020-08-12 22:51
 */
@Service
public class SpotServiceImpl implements SpotService {
    @Autowired
    private SpotRepository spotRepository;

    @Autowired
    private MongoTemplate mongoTemplate;


    @Override
    public void save(Spot spot) {
        spot.setId(null);
        spotRepository.insert(spot);
    }

    @Override
    public void update(Spot spot) {
        spotRepository.save(spot);
    }

    @Override
    public void delete(String id) {
        spotRepository.deleteById(id);
    }

    @Override
    public Spot get(String id) {
        return spotRepository.findById(id).orElse(null);
    }

    @Override
    public List<Spot> list() {
        return spotRepository.findAll();
    }

    /**
    * 景点高级查询
    * @param qo 查询条件
    * @return
    */
    @Override
    public Page<Spot> query(SpotQueryObject qo) {

        Query query = new Query();

        long count = mongoTemplate.count(query, Spot.class);
        if (count == 0) {
            return Page.empty();
        }

        Pageable pageRequest = PageRequest.of(qo.getCurrentPage()-1,qo.getPageSize(), Sort.Direction.ASC,"sequence");
        query.with(pageRequest);
        List<Spot> list = mongoTemplate.find(query, Spot.class);
        return new PageImpl<Spot>(list,pageRequest,count);
    }

    /**
     * 新增或编辑景点
     * @param spot
     */
    @Override
    public void saveOrUpdate(Spot spot) {
        if (StringUtils.hasLength(spot.getId())) {
            //编辑
            this.update(spot);
        }else {
            //新增
            this.save(spot);
        }
    }
}
